import ImageCompressor from "image-compressor.js";
import UPNG from 'upng-js';
// 压缩图片  一般在上传前调用
export function compressImage(file) {
	const fileData = file.file
	return new Promise(async (resolve, reject) => {
		if (fileData.size / 1024 / 1024 > 1) {
			// 判断是否是真实的png图片
			const isPng = await isPNG(fileData)
			if (isPng) {
				// Png 压缩 10MB以上再压缩
				if (fileData.size / 1024 / 1024 > 10) {
					const compressdedPng = await compressPNG(fileData)
					resolve(compressdedPng)
				} else {
					resolve(fileData);
				}

			} else {
				new ImageCompressor(fileData, {
					quality: 0.6,
					checkOrientation: false,
					mimeType: "image/jpeg",
					// width:1920,
					success(result) {
						resolve(result);
					},
					error(e) {
						reject();
					},
				});
			}
		} else {
			resolve(fileData);
		}
	});
}
// 是否PNG图片
async function isPNG(file) {
	const buffer = await readFileAsArrayBuffer(file, 8); // 读取前8字节
	const uint8Array = new Uint8Array(buffer);
	const pngHeader = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
	return pngHeader.every((byte, index) => byte === uint8Array[index]);
}
// 压缩PNG图片
// 压缩 PNG
async function compressPNG(file) {
	try {
		const arrayBuffer = await readFileAsArrayBuffer(file);
		const imageNuffer = UPNG.decode(arrayBuffer); // 解码 PNG
		const imgData = alignTo4Bytes(imageNuffer.data)
		// 压缩参数：质量（0-1）、颜色位数（256 为有损压缩）
		const compressed = UPNG.encode(
			[imgData],
			imageNuffer.width,
			imageNuffer.height,
			256 * 0.7 // 70% 质量
		);
		// 转换为 Blob 并更新响应式数据
		const blob = new Blob([compressed], { type: "image/png" });
		return blob
	} catch (error) {
		console.error("压缩失败:", error);
	}
}
// 手动对齐
function alignTo4Bytes(data) {
	const remainder = data.length % 4;
	if (remainder === 0) return data;
	const aligned = new Uint8Array(data.length + (4 - remainder));
	aligned.set(data);
	return aligned;
}
//文件读取为buffer
function readFileAsArrayBuffer(file, end) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.onload = (e) => resolve(e.target.result);
		reader.onerror = (e) => reject(e);
		if (end) {
			reader.readAsArrayBuffer(file.slice(0, end));
		} else {
			reader.readAsArrayBuffer(file);
		}

	});
}